package org.jash.launcher.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.jash.common.adapter.CommonAdapter
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseFragment
import org.jash.launcher.R
import org.jash.launcher.BR
import org.jash.launcher.databinding.FragmentGatewayBinding
import org.jash.launcher.entity.GatewayEntity
import org.jash.launcher.model.GatewayIntent
import org.jash.launcher.model.GatewayState
import org.jash.launcher.model.GatewayViewModel
import java.util.Calendar


/**
 * A simple [Fragment] subclass.
 * Use the [GatewayFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class GatewayFragment : BaseFragment<FragmentGatewayBinding, GatewayViewModel>() {
    val adapter by lazy { CommonAdapter<GatewayEntity>(map = {d ->
        when(d.typeId) {
            100 -> R.layout.item_gateway_category to BR.gateway
            200 -> R.layout.item_gateway_app to BR.gateway
            300 -> R.layout.item_gateway_placeholder to BR.gateway
            else -> R.layout.item_gateway_category to BR.gateway
        }
    }, span = { d ->
        when(d.typeId) {
            100 -> 3
            200 -> 1
            300 -> 3
            else -> 1
        }
    }
        ) }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        binding.date.text = "$day"
        binding.recycler.adapter = adapter
        lifecycleScope.launch {
            viewModel.intent.send(GatewayIntent.CreateGateway)
        }


    }
    fun loadedGateway(response: GatewayState.Response) {
//        response.data.forEach(this::logDebug)
        adapter += response.data
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         * @return A new instance of fragment GatewayFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance() =
            GatewayFragment()
    }
}